import * as echarts from '../../ec-canvas/echarts'

let chart = null

function initChart(canvas, width, height, dpr) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  })
  canvas.setChart(chart)

  const option = {
    title: {
      text: '盈亏趋势分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      name: '盈亏金额'
    },
    series: [{
      name: '盈亏',
      type: 'line',
      data: []
    }]
  }

  chart.setOption(option)
  return chart
}

Page({
  data: {
    ec: {
      onInit: initChart
    },
    summary: {
      total: 0,
      average: 0
    }
  },

  onLoad() {
    this.loadData()
  },

  async loadData() {
    try {
      // 从云数据库获取最新的分析数据
      const db = wx.cloud.database()
      const res = await db.collection('analysis_data')
        .orderBy('createTime', 'desc')
        .limit(1)
        .get()

      if (res.data.length > 0) {
        const analysisData = res.data[0].data
        this.processData(analysisData)
      }
    } catch (error) {
      console.error('加载数据失败', error)
      wx.showToast({
        title: '加载数据失败',
        icon: 'none'
      })
    }
  },

  processData(data) {
    // 处理数据用于图表显示
    const dates = []
    const values = []
    let total = 0

    data.forEach(item => {
      dates.push(item.日期)
      values.push(item.盈亏金额)
      total += Number(item.盈亏金额)
    })

    const average = total / data.length

    // 更新图表
    const option = {
      xAxis: {
        data: dates
      },
      series: [{
        data: values
      }]
    }
    chart.setOption(option)

    // 更新统计数据
    this.setData({
      summary: {
        total: total.toFixed(2),
        average: average.toFixed(2)
      }
    })
  }
}) 